import cv2
import numpy as np


def process_plate_image(image_path):
    # 读取图像
    image = cv2.imread(image_path)

    if image is None:
        print(f"无法读取图像: {image_path}")
        return

    # 创建窗口
    cv2.namedWindow('交互式HSV车牌处理', cv2.WINDOW_NORMAL)
    cv2.resizeWindow('交互式HSV车牌处理', 1000, 400)  # 调整窗口高度

    # 初始化HSV参数
    h_min, s_min, v_min = 0, 0, 0
    h_max, s_max, v_max = 180, 255, 255

    # 创建滑动条
    def nothing(x):
        pass

    cv2.createTrackbar('H Min', '交互式HSV车牌处理', h_min, 180, nothing)
    cv2.createTrackbar('S Min', '交互式HSV车牌处理', s_min, 255, nothing)
    cv2.createTrackbar('V Min', '交互式HSV车牌处理', v_min, 255, nothing)
    cv2.createTrackbar('H Max', '交互式HSV车牌处理', h_max, 180, nothing)
    cv2.createTrackbar('S Max', '交互式HSV车牌处理', s_max, 255, nothing)
    cv2.createTrackbar('V Max', '交互式HSV车牌处理', v_max, 255, nothing)

    # 主循环
    while True:
        # 获取滑动条当前值
        h_min = cv2.getTrackbarPos('H Min', '交互式HSV车牌处理')
        s_min = cv2.getTrackbarPos('S Min', '交互式HSV车牌处理')
        v_min = cv2.getTrackbarPos('V Min', '交互式HSV车牌处理')
        h_max = cv2.getTrackbarPos('H Max', '交互式HSV车牌处理')
        s_max = cv2.getTrackbarPos('S Max', '交互式HSV车牌处理')
        v_max = cv2.getTrackbarPos('V Max', '交互式HSV车牌处理')

        # 转换为HSV格式
        hsv_image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)

        # 创建HSV掩码
        lower = np.array([h_min, s_min, v_min])
        upper = np.array([h_max, s_max, v_max])
        mask = cv2.inRange(hsv_image, lower, upper)

        # 应用掩码
        result = cv2.bitwise_and(image, image, mask=mask)

        # 只显示原图和处理后的图像
        combined = np.hstack((image, result))

        # 添加参数信息
        param_text = f'H: {h_min}-{h_max}, S: {s_min}-{s_max}, V: {v_min}-{v_max}'
        cv2.putText(combined, param_text, (10, 30),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2)

        cv2.imshow('交互式HSV车牌处理', combined)

        # 按ESC键退出
        if cv2.waitKey(1) & 0xFF == 27:
            break

    cv2.destroyAllWindows()


# 请替换为实际的图像路径
image_path = "3.png"  # 车牌照片3的路径
process_plate_image(image_path)